﻿using PRO.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using PRO.Common;

namespace PRO.ORM
{
    public abstract class SqlHelper
    {
        private string _TableName;
        /// <summary>
        /// 操作的表名
        /// </summary>
        public string TableName
        {
            get { return _TableName; }
            set { _TableName = value; }
        }
        private int _TopCounts;
        /// <summary>
        /// 查询前几条数据
        /// </summary>
        public int TopCounts
        {
            get { return _TopCounts; }
            set { _TopCounts = value; }
        }
        private string _OrderBy;
        /// <summary>
        /// 查询排序，例如： order by id desc
        /// </summary>
        public string OrderBy
        {
            get { return _OrderBy; }
            set { _OrderBy = value; }
        }
        private string _GroupBy;
        /// <summary>
        /// 查询分组,例如：group by id
        /// </summary>
        public string GroupBy
        {
            get { return _GroupBy; }
            set { _GroupBy = value; }
        }
        /// <summary>
        /// 执行操作
        /// </summary>
        /// <returns></returns>
        public abstract object Run();
        /// <summary>
        /// 添加实体类
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="NotExeFeild">不需要对数据操作的字段名</param>
        public abstract void AddEntity<T>(T entity, params string[] NotExeFeild) where T : BaseEntity;
        /// <summary>
        /// 添加字段(一般在插入、更新、删除操作里使用)
        /// </summary>
        /// <param name="feild">字段名</param>
        /// <param name="value">字段值</param>
        /// <param name="type">字段类型</param>
        /// <param name="len">字段长度</param>
        public abstract void AddFeild(string feild, object value, SqlDbType type, int len);
        /// <summary>
        /// 添加字段（一般在查询的时候使用，不用指定列的值和数据类型）
        /// </summary>
        /// <param name="feilds"></param>
        public abstract void AddFeild(params string[] feilds);
        /// <summary>
        /// 添加And 筛选字段
        /// </summary>
        /// <param name="feild">字段名</param>
        /// <param name="value">字段值</param>
        /// <param name="type">字段数据类型</param>
        /// <param name="len">字段长度</param>
        /// <param name="oper">操作符">,=,<,<>,>=,<="</param>
        public abstract void AddWhereAnd(string feild, object value, SqlDbType type, int len, string oper);
        /// <summary>
        /// 添加Or 筛选字段
        /// </summary>
        /// <param name="feild">字段名</param>
        /// <param name="value">字段值</param>
        /// <param name="type">字段数据类型</param>
        /// <param name="len">字段长度</param>
        /// <param name="oper">操作符">,=,<,<>,>=,<="</param>
        public abstract void AddWhereOr(string feild, object value, SqlDbType type, int len, string oper);

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="feilds"></param>
        /// <param name="where_and_feilds"></param>
        /// <param name="where_or_feilds"></param>
        /// <param name="NotExeFeilds"></param>
        /// <returns></returns>
        protected int Insert(string tab, List<EntityAttributeInfo> feilds, List<WhereInfo> where_and_feilds, List<WhereInfo> where_or_feilds)
        {
            if (!string.IsNullOrWhiteSpace(tab))
            {
                if (feilds.Count > 0)
                {
                    List<DbParameter> p = new List<DbParameter>();
                    StringBuilder sql_fields = new StringBuilder();
                    StringBuilder sql_values = new StringBuilder();
                    sql_fields.AppendFormat("insert into {0}(", tab);
                    sql_values.AppendFormat(" values(");
                    int i = 0;
                    foreach (EntityAttributeInfo feild in feilds)
                    {
                        if (!feild.PrimaryKey)
                        {
                            p.Add(DbHelper.MakeInParam("@" + feild.Feild, (DbType)feild.SqlDbType, feild.Len, feild.Value));
                            if (i == 0)
                            {
                                sql_fields.Append(feild.Feild);
                                sql_values.AppendFormat("@{0}", feild.Feild);
                            }
                            else
                            {
                                sql_fields.AppendFormat(",{0}", feild.Feild);
                                sql_values.AppendFormat(",@{0}", feild.Feild);
                            }
                            i++;
                        }
                    }
                    sql_fields.Append(")");
                    sql_values.Append(")");
                    sql_fields.Append(sql_values.ToString() + ";select @@IDENTITY;");
                    DbParameter[] prams = p.ToArray();
                    return int.Parse(DbHelper.ExecuteScalar(CommandType.Text, sql_fields.ToString(), prams).ToString());
                }
                else
                    throw new Exception("必须为插入的数据指定列！");
            }
            else
                throw new Exception("插入数据必须指定目标表名！");
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="feilds"></param>
        /// <param name="where_and_feilds"></param>
        /// <param name="where_or_feilds"></param>
        /// <returns></returns>
        protected bool Delete(string tab, List<EntityAttributeInfo> feilds, List<WhereInfo> where_and_feilds, List<WhereInfo> where_or_feilds)
        {
            if (string.IsNullOrWhiteSpace(tab))
                throw new Exception("删除数据必须指定目标表名");
            else
            {
                if (where_and_feilds.Count == 0 && where_or_feilds.Count == 0 && feilds.Count == 0)
                    throw new Exception("删除时必须传入删除条件！");
                else
                {
                    List<DbParameter> p = new List<DbParameter>();
                    StringBuilder sql = new StringBuilder();
                    sql.AppendFormat("delete {0} where 0=0 ", tab);
                    if (feilds.Count > 0)
                    {
                        //if (feilds.FindAll(delegate(EntityAttributeInfo info) { return info.PrimaryKey == true; }).Count == 0)
                        //    throw new Exception("没有指定主键列！");
                        //else
                        //{
                        foreach (EntityAttributeInfo item in feilds)
                        {
                            sql.AppendFormat(" and {0}=@{0}", item.Feild);
                            p.Add(DbHelper.MakeInParam("@" + item.Feild, (DbType)item.SqlDbType, item.Len, item.Value));
                        }
                        //}
                    }
                    if (where_and_feilds.Count > 0)
                    {
                        foreach (WhereInfo item in where_and_feilds)
                        {
                            sql.AppendFormat(" and {0}{2}@{1}", item.Feild, item.ParamName, item.Operator);
                            p.Add(DbHelper.MakeInParam("@" + item.ParamName, (DbType)item.SqlDbType, item.Len, item.Value));
                        }
                    }
                    if (where_or_feilds.Count > 0)
                    {
                        if (where_or_feilds.Count == 1)
                        {
                            sql.AppendFormat(" or {0}{2}@{1}", where_or_feilds[0].Feild, where_or_feilds[0].ParamName, where_or_feilds[0].Operator);
                            p.Add(DbHelper.MakeInParam("@" + where_or_feilds[0].ParamName, (DbType)where_or_feilds[0].SqlDbType, where_or_feilds[0].Len, where_or_feilds[0].Value));
                        }
                        else
                        {
                            sql.Append("(");
                            for (int i = 0; i < where_or_feilds.Count; i++)
                            {
                                sql.AppendFormat(" {3} {0}{2}@{1}", where_or_feilds[i].Feild, where_or_feilds[i].ParamName, where_or_feilds[i].Operator, (i > 0) ? "or" : "");
                                p.Add(DbHelper.MakeInParam("@" + where_or_feilds[i].ParamName, (DbType)where_or_feilds[i].SqlDbType, where_or_feilds[i].Len, where_or_feilds[i].Value));
                            }
                            sql.Append(")");
                        }
                    }
                    return Convert.ToBoolean(DbHelper.ExecuteNonQuery(CommandType.Text, sql.ToString(), p.ToArray()));
                }
            }
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="feilds"></param>
        /// <param name="where_and_feilds"></param>
        /// <param name="where_or_feilds"></param>
        /// <returns></returns>
        protected bool Update(string tab, List<EntityAttributeInfo> feilds, List<WhereInfo> where_and_feilds, List<WhereInfo> where_or_feilds)
        {
            if (string.IsNullOrWhiteSpace(tab))
                throw new Exception("更新数据必须指定目标表名");
            else
            {
                if (where_and_feilds.Count == 0 && where_or_feilds.Count == 0 && feilds.Count == 0)
                    throw new Exception("更新时必须传入更新条件及更新的列！");
                else
                {
                    List<DbParameter> p = new List<DbParameter>();
                    StringBuilder sql = new StringBuilder();
                    StringBuilder sql_where = new StringBuilder();
                    sql_where.Append(" where 0=0 ");
                    sql.AppendFormat("update {0} set ", tab);
                    bool Exist_PrimaryKey = false;//是否有主键列
                    if (feilds.Count > 0)
                    {
                        int counts = 0;
                        foreach (EntityAttributeInfo item in feilds)
                        {
                            if (item.PrimaryKey)
                            {
                                Exist_PrimaryKey = true;
                                sql_where.AppendFormat(" and {0}=@{0}", item.Feild);
                            }
                            else
                            {
                                if (counts == 0)
                                    sql.AppendFormat("{0}=@{0}", item.Feild);
                                else
                                    sql.AppendFormat(",{0}=@{0}", item.Feild);
                                counts++;
                            }
                            p.Add(DbHelper.MakeInParam("@" + item.Feild, (DbType)item.SqlDbType, item.Len, item.Value));
                        }
                    }
                    else
                        throw new Exception("更新时必须指定需要更新的列！");

                    if (!Exist_PrimaryKey && where_or_feilds.Count == 0 && feilds.Count == 0)
                        throw new Exception("更新时必须有更新条件！");
                    else
                    {
                        if (where_and_feilds.Count > 0)
                        {
                            foreach (WhereInfo item in where_and_feilds)
                            {
                                sql_where.AppendFormat(" and {0}{2}@{1}", item.Feild, item.ParamName, item.Operator);
                                p.Add(DbHelper.MakeInParam("@" + item.ParamName, (DbType)item.SqlDbType, item.Len, item.Value));
                            }
                        }
                        if (where_or_feilds.Count > 0)
                        {
                            if (where_or_feilds.Count == 1)
                            {
                                sql_where.AppendFormat(" or {0}{2}@{1}", where_or_feilds[0].Feild, where_or_feilds[0].ParamName, where_or_feilds[0].Operator);
                                p.Add(DbHelper.MakeInParam("@" + where_or_feilds[0].ParamName, (DbType)where_or_feilds[0].SqlDbType, where_or_feilds[0].Len, where_or_feilds[0].Value));
                            }
                            else
                            {
                                sql_where.Append(" or (");
                                for (int i = 0; i < where_or_feilds.Count; i++)
                                {
                                    sql_where.AppendFormat(" {3} {0}{2}@{1}", where_or_feilds[i].Feild, where_or_feilds[i].ParamName, where_or_feilds[i].Operator, (i > 0) ? "or" : "");
                                    p.Add(DbHelper.MakeInParam("@" + where_or_feilds[i].ParamName, (DbType)where_or_feilds[i].SqlDbType, where_or_feilds[i].Len, where_or_feilds[i].Value));
                                }
                                sql_where.Append(")");
                            }
                        }
                    }
                    return Convert.ToBoolean(DbHelper.ExecuteNonQuery(CommandType.Text, sql.ToString() + sql_where.ToString(), p.ToArray()));
                }
            }
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="feilds"></param>
        /// <param name="where_and_feilds"></param>
        /// <param name="where_or_feilds"></param>
        /// <returns></returns>
        protected DataTable Select(string tab, int counts, string groupby, string orderby, List<EntityAttributeInfo> feilds, List<WhereInfo> where_and_feilds, List<WhereInfo> where_or_feilds)
        {
            if (string.IsNullOrWhiteSpace(tab))
                throw new Exception("更新数据必须指定目标表名");
            else
            {
                StringBuilder sql = new StringBuilder();
                if (feilds.Count > 0)
                {
                    sql.AppendFormat("select {0} ", (counts > 0) ? " top " + counts : "");
                    for (int i = 0; i < feilds.Count; i++)
                    {
                        sql.AppendFormat("{0}{1}", (i == 0) ? "" : ",", feilds[i].Feild);
                    }
                    sql.AppendFormat(" from {0}", tab);
                }
                else
                    throw new Exception("必须指定查询列！");

                StringBuilder sql_where = new StringBuilder();
                sql_where.Append(" where 0=0 ");
                List<DbParameter> p = new List<DbParameter>();
                if (where_and_feilds.Count > 0)
                {
                    foreach (WhereInfo item in where_and_feilds)
                    {
                        sql_where.AppendFormat(" and {0}{2}@{1}", item.Feild, item.ParamName, item.Operator);
                        p.Add(DbHelper.MakeInParam("@" + item.ParamName, (DbType)item.SqlDbType, item.Len, item.Value));
                    }
                }
                if (where_or_feilds.Count > 0)
                {
                    if (where_or_feilds.Count == 1)
                    {
                        sql_where.AppendFormat(" or {0}{2}@{1}", where_or_feilds[0].Feild, where_or_feilds[0].ParamName, where_or_feilds[0].Operator);
                        p.Add(DbHelper.MakeInParam("@" + where_or_feilds[0].ParamName, (DbType)where_or_feilds[0].SqlDbType, where_or_feilds[0].Len, where_or_feilds[0].Value));
                    }
                    else
                    {
                        sql_where.Append(" or (");
                        for (int i = 0; i < where_or_feilds.Count; i++)
                        {
                            sql_where.AppendFormat(" {3} {0}{2}@{1}", where_or_feilds[i].Feild, where_or_feilds[i].ParamName, where_or_feilds[i].Operator, (i > 0) ? "or" : "");
                            p.Add(DbHelper.MakeInParam("@" + where_or_feilds[i].ParamName, (DbType)where_or_feilds[i].SqlDbType, where_or_feilds[i].Len, where_or_feilds[i].Value));
                        }
                        sql_where.Append(")");
                    }
                }

                sql_where.AppendFormat(" {0} {1}", groupby, orderby);
                return DbHelper.ExecuteDataset(CommandType.Text, sql.ToString() + sql_where.ToString(), p.ToArray()).Tables[0];
            }
        }
    }
    /// <summary>
    /// 数据库插入数据操作
    /// </summary>
    public class SqlInsert : SqlHelper
    {
        List<EntityAttributeInfo> feilds = new List<EntityAttributeInfo>();
        List<WhereInfo> where_and_feilds = new List<WhereInfo>();
        List<WhereInfo> where_or_feilds = new List<WhereInfo>();
        public SqlInsert()
        { }
        public SqlInsert(string tabname)
        {
            this.TableName = tabname;
        }
        public override object Run()
        {
            return Insert(this.TableName, feilds, where_and_feilds, where_or_feilds);
        }
        /// <summary>
        /// 添加实体类
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="NotExeFeild">不需要对数据操作的字段名</param>
        public override void AddEntity<T>(T entity, params string[] NotExeFeilds)
        {
            string tabname = EntityAttributeLib.GetTableName(entity);
            if (!string.IsNullOrWhiteSpace(tabname))
                this.TableName = tabname;
            feilds = EntityAttributeLib.GetProperties(entity, feilds, NotExeFeilds);
        }
        /// <summary>
        /// 添加字段
        /// </summary>
        /// <param name="feild">字段名</param>
        /// <param name="value">字段值</param>
        /// <param name="type">字段类型</param>
        /// <param name="len">字段长度</param>
        public override void AddFeild(string feild, object value, SqlDbType type, int len)
        {
            if (string.IsNullOrWhiteSpace(feild))
            {
                throw new Exception("指定的列名不能为空！");
            }
            else
            {
                if (feilds.FindAll(delegate(EntityAttributeInfo info) { return info.Feild.ToLower() == feild.ToLower(); }).Count > 0)
                    throw new Exception("已存在字段名：" + feild + "！");
                else
                {
                    EntityAttributeInfo info = new EntityAttributeInfo();
                    info.Feild = feild.ToLower();
                    info.Value = value;
                    info.Len = len;
                    info.SqlDbType = type;
                    feilds.Add(info);
                }
            }
        }
        public override void AddFeild(params string[] feilds)
        {
            throw new Exception("必须给插入列指定值和数据类型！");
        }
        public override void AddWhereAnd(string feild, object value, SqlDbType type, int len, string oper)
        {
            return;
        }
        public override void AddWhereOr(string feild, object value, SqlDbType type, int len, string oper)
        {
            return;
        }
    }
    /// <summary>
    /// 数据库更新操作
    /// </summary>
    public class SqlUpdate : SqlHelper
    {
        List<EntityAttributeInfo> feilds = new List<EntityAttributeInfo>();
        List<WhereInfo> where_and_feilds = new List<WhereInfo>();
        List<WhereInfo> where_or_feilds = new List<WhereInfo>();
        public SqlUpdate()
        { }
        public SqlUpdate(string tab)
        {
            this.TableName = tab;
        }
        public override object Run()
        {
            return Update(this.TableName, feilds, where_and_feilds, where_or_feilds);
        }
        public override void AddEntity<T>(T entity, params string[] NotExeFeilds)
        {
            string tabname = EntityAttributeLib.GetTableName(entity);
            if (!string.IsNullOrWhiteSpace(tabname))
                this.TableName = tabname;
            feilds = EntityAttributeLib.GetProperties(entity, feilds, NotExeFeilds);
        }
        public override void AddFeild(string feild, object value, SqlDbType type, int len)
        {
            if (string.IsNullOrWhiteSpace(feild))
            {
                throw new Exception("指定的列名不能为空！");
            }
            else
            {
                if (feilds.FindAll(delegate(EntityAttributeInfo info) { return info.Feild.ToLower() == feild.ToLower(); }).Count > 0)
                    throw new Exception("已存在字段名：" + feild + "！");
                else
                {
                    EntityAttributeInfo info = new EntityAttributeInfo();
                    info.Feild = feild.ToLower();
                    info.Value = value;
                    info.Len = len;
                    info.SqlDbType = type;
                    feilds.Add(info);
                }
            }
        }
        public override void AddFeild(params string[] feild)
        {
            throw new Exception("更新列必须指定值和数据类型！");
        }
        public override void AddWhereAnd(string feild, object value, SqlDbType type, int len, string oper)
        {
            if (string.IsNullOrWhiteSpace(feild))
                throw new Exception("指定的列名不能为空！");
            else if (string.IsNullOrWhiteSpace(oper))
                throw new Exception("操作符不能为空！");
            else
            {
                if (where_and_feilds.FindAll(delegate(WhereInfo info) { return info.Feild.ToLower() == feild.ToLower(); }).Count > 0)
                    throw new Exception("已存在筛选字段：" + feild.ToLower() + "！");
                else
                {
                    WhereInfo info = new WhereInfo();
                    info.Feild = feild.ToLower();
                    info.ParamName = "where_and_" + feild.ToLower();
                    info.Value = value;
                    info.Operator = oper;
                    info.SqlDbType = type;
                    info.Len = len;
                    where_and_feilds.Add(info);
                }
            }
        }
        public override void AddWhereOr(string feild, object value, SqlDbType type, int len, string oper)
        {
            if (string.IsNullOrWhiteSpace(feild))
                throw new Exception("指定的列名不能为空！");
            else if (string.IsNullOrWhiteSpace(oper))
                throw new Exception("操作符不能为空！");
            else
            {
                if (where_or_feilds.FindAll(delegate(WhereInfo info) { return info.Feild.ToLower() == feild.ToLower(); }).Count > 0)
                    throw new Exception("已存在筛选字段：" + feild.ToLower() + "！");
                else
                {
                    WhereInfo info = new WhereInfo();
                    info.Feild = feild.ToLower();
                    info.ParamName = "where_or_" + feild.ToLower();
                    info.Value = value;
                    info.Operator = oper;
                    info.SqlDbType = type;
                    info.Len = len;
                    where_or_feilds.Add(info);
                }
            }
        }
    }
    /// <summary>
    /// 数据库数据删除操作
    /// </summary>
    public class SqlDelete : SqlHelper
    {
        List<EntityAttributeInfo> feilds = new List<EntityAttributeInfo>();
        List<WhereInfo> where_and_feilds = new List<WhereInfo>();
        List<WhereInfo> where_or_feilds = new List<WhereInfo>();
        public SqlDelete()
        { }
        public SqlDelete(string tab)
        {
            this.TableName = tab;
        }
        public override object Run()
        {
            return Delete(this.TableName, feilds, where_and_feilds, where_or_feilds);
        }
        public override void AddEntity<T>(T entity, params string[] NotExeFeilds)
        {
            string tabname = EntityAttributeLib.GetTableName(entity);
            if (!string.IsNullOrWhiteSpace(tabname))
                this.TableName = tabname;
            feilds = EntityAttributeLib.GetProperties(entity, feilds, NotExeFeilds);
        }
        public override void AddFeild(string feild, object value, SqlDbType type, int len)
        {
            if (string.IsNullOrWhiteSpace(feild))
            {
                throw new Exception("指定的列名不能为空！");
            }
            else
            {
                if (feilds.FindAll(delegate(EntityAttributeInfo info) { return info.Feild.ToLower() == feild.ToLower(); }).Count > 0)
                    throw new Exception("已存在字段名：" + feild + "！");
                else
                {
                    EntityAttributeInfo info = new EntityAttributeInfo();
                    info.Feild = feild.ToLower();
                    info.Value = value;
                    info.Len = len;
                    info.SqlDbType = type;
                    feilds.Add(info);
                }
            }
        }
        public override void AddFeild(params string[] feild)
        {
            throw new Exception("删除数据必须指定列的值和数据类型！");
        }
        public override void AddWhereAnd(string feild, object value, SqlDbType type, int len, string oper)
        {
            if (string.IsNullOrWhiteSpace(feild))
                throw new Exception("指定的列名不能为空！");
            else if (string.IsNullOrWhiteSpace(oper))
                throw new Exception("操作符不能为空！");
            else
            {
                if (where_and_feilds.FindAll(delegate(WhereInfo info) { return info.Feild.ToLower() == feild.ToLower(); }).Count > 0)
                    throw new Exception("已存在筛选字段：" + feild.ToLower() + "！");
                else
                {
                    WhereInfo info = new WhereInfo();
                    info.Feild = feild.ToLower();
                    info.ParamName = "where_and_" + feild.ToLower();
                    info.Value = value;
                    info.Operator = oper;
                    info.SqlDbType = type;
                    info.Len = len;
                    where_and_feilds.Add(info);
                }
            }
        }
        public override void AddWhereOr(string feild, object value, SqlDbType type, int len, string oper)
        {
            if (string.IsNullOrWhiteSpace(feild))
                throw new Exception("指定的列名不能为空！");
            else if (string.IsNullOrWhiteSpace(oper))
                throw new Exception("操作符不能为空！");
            else
            {
                if (where_or_feilds.FindAll(delegate(WhereInfo info) { return info.Feild.ToLower() == feild.ToLower(); }).Count > 0)
                    throw new Exception("已存在筛选字段：" + feild.ToLower() + "！");
                else
                {
                    WhereInfo info = new WhereInfo();
                    info.Feild = feild.ToLower();
                    info.ParamName = "where_or_" + feild.ToLower();
                    info.Value = value;
                    info.Operator = oper;
                    info.SqlDbType = type;
                    info.Len = len;
                    where_or_feilds.Add(info);
                }
            }
        }
    }
    /// <summary>
    /// 数据库查询
    /// </summary>
    public class SqlSelect : SqlHelper
    {
        List<EntityAttributeInfo> feilds = new List<EntityAttributeInfo>();
        List<WhereInfo> where_and_feilds = new List<WhereInfo>();
        List<WhereInfo> where_or_feilds = new List<WhereInfo>();

        public SqlSelect()
        { }
        public SqlSelect(string tab)
        {
            this.TableName = tab;
        }

        public override void AddFeild(params string[] feild)
        {
            if (feild.Length > 0)
            {
                foreach (string f in feild)
                {
                    if (!string.IsNullOrWhiteSpace(f))
                    {
                        if (feilds.FindAll(delegate(EntityAttributeInfo info) { return info.Feild.ToLower() == f.ToLower(); }).Count > 0)
                            throw new Exception("已存在字段名：" + f + "！");
                        else
                        {
                            EntityAttributeInfo info = new EntityAttributeInfo();
                            info.Feild = f.ToLower();
                            info.Value = null;
                            info.Len = 0;
                            info.SqlDbType = SqlDbType.NVarChar;
                            feilds.Add(info);
                        }
                    }
                }
            }
        }

        public override void AddEntity<T>(T entity, params string[] NotExeFeilds)
        {
            string tabname = EntityAttributeLib.GetTableName(entity);
            if (!string.IsNullOrWhiteSpace(tabname))
                this.TableName = tabname;
            feilds = EntityAttributeLib.GetProperties(entity, feilds, NotExeFeilds);
        }
        public override void AddFeild(string feild, object value, SqlDbType type, int len)
        {
            this.AddFeild(feild);
        }
        public override void AddWhereAnd(string feild, object value, SqlDbType type, int len, string oper)
        {
            if (string.IsNullOrWhiteSpace(feild))
                throw new Exception("指定的列名不能为空！");
            else if (string.IsNullOrWhiteSpace(oper))
                throw new Exception("操作符不能为空！");
            else
            {
                if (where_and_feilds.FindAll(delegate(WhereInfo info) { return info.Feild.ToLower() == feild.ToLower(); }).Count > 0)
                    throw new Exception("已存在筛选字段：" + feild.ToLower() + "！");
                else
                {
                    WhereInfo info = new WhereInfo();
                    info.Feild = feild.ToLower();
                    info.ParamName = "where_and_" + feild.ToLower();
                    info.Value = value;
                    info.Operator = oper;
                    info.SqlDbType = type;
                    info.Len = len;
                    where_and_feilds.Add(info);
                }
            }
        }
        public override void AddWhereOr(string feild, object value, SqlDbType type, int len, string oper)
        {
            if (string.IsNullOrWhiteSpace(feild))
                throw new Exception("指定的列名不能为空！");
            else if (string.IsNullOrWhiteSpace(oper))
                throw new Exception("操作符不能为空！");
            else
            {
                if (where_or_feilds.FindAll(delegate(WhereInfo info) { return info.Feild.ToLower() == feild.ToLower(); }).Count > 0)
                    throw new Exception("已存在筛选字段：" + feild.ToLower() + "！");
                else
                {
                    WhereInfo info = new WhereInfo();
                    info.Feild = feild.ToLower();
                    info.ParamName = "where_or_" + feild.ToLower();
                    info.Value = value;
                    info.Operator = oper;
                    info.SqlDbType = type;
                    info.Len = len;
                    where_or_feilds.Add(info);
                }
            }
        }


        public override object Run()
        {
            return Select(this.TableName, this.TopCounts, this.GroupBy, this.OrderBy, feilds, where_and_feilds, where_or_feilds);
        }
    }

    /// <summary>
    /// ORM数据库操作扩展类
    /// </summary>
    public static class SqlHelperExpand
    {
        /// <summary>
        /// 将数据更新到数据库
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="NoExeFeilds">不执行操作的字段</param>
        /// <returns></returns>
        public static bool Update<T>(this T entity, params string[] NoExeFeilds) where T : BaseEntity
        {
            SqlHelper helper = new SqlUpdate();
            helper.AddEntity(entity, NoExeFeilds);
            return helper.Run().ToString().ToBoolean(false);
        }
        /// <summary>
        /// 将数据插入到数据库
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="NoExeFeilds">不执行操作的字段</param>
        /// <returns></returns>
        public static int Insert<T>(this T entity, params string[] NoExeFeilds) where T : BaseEntity
        {
            SqlHelper helper = new SqlInsert();
            helper.AddEntity(entity, NoExeFeilds);
            return helper.Run().ToString().ToInt(0);
        }
        /// <summary>
        /// 将数据从数据库删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="NoExeFeilds">需要忽略的字段</param>
        /// <returns></returns>
        public static bool Delete<T>(this T entity, params string[] NoExeFeilds) where T : BaseEntity
        {
            SqlHelper helper = new SqlDelete();
            helper.AddEntity(entity, NoExeFeilds);
            return helper.Run().ToString().ToBoolean(false);
        }
    }
    /// <summary>
    /// 数据转化扩展类
    /// </summary>
    public static class DataBindLib
    {
        /// <summary>
        /// 给实体类绑定数据，绑定数据表的第一行数据
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="dt">数据表</param>
        /// <param name="NoExeFeilds">不用绑定值的字段</param>
        public static void BindDataToEntity<T>(this T entity, DataTable dt, params string[] NoExeFeilds) where T : BaseEntity
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                entity.BindDataToEntity(dt.Rows[0], NoExeFeilds);
            }
        }
        /// <summary>
        /// 给实体类绑定数据，绑定数据列的第一行数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="rows"></param>
        /// <param name="NoExeFeilds">不用绑定值的字段</param>
        public static void BindDataToEntity<T>(this T entity, DataRow[] rows, params string[] NoExeFeilds) where T : BaseEntity
        {
            if (rows != null && rows.Length > 0)
                entity.BindDataToEntity(rows[0], NoExeFeilds);
        }
        /// <summary>
        /// 给实体类绑定数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="dt">数据表</param>
        /// <param name="NoExeFeilds">不用绑定值的字段</param>
        public static void BindDataToEntity<T>(this List<T> entity, DataTable dt, params string[] NoExeFeilds) where T : BaseEntity
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    T t = (T)Activator.CreateInstance(typeof(T));
                    t.BindDataToEntity(dt.Rows[i], NoExeFeilds);
                    entity.Add(t);
                }
            }
        }
        /// <summary>
        /// 给实体类绑定数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="rows">多数据行</param>
        /// <param name="NoExeFeilds">不用绑定值的字段</param>
        public static void BindDataToEntity<T>(this List<T> entity, DataRow[] rows, params string[] NoExeFeilds) where T : BaseEntity
        {
            if (rows.Length > 0)
            {
                for (int i = 0; i < rows.Length; i++)
                {
                    T t = (T)Activator.CreateInstance(typeof(T));
                    t.BindDataToEntity(rows[i], NoExeFeilds);
                    entity.Add(t);
                }
            }
        }
        /// <summary>
        /// 给实体类绑定数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="row">单数据行</param>
        /// <param name="NoExeFeilds">不用绑定值的字段</param>
        public static void BindDataToEntity<T>(this T entity, DataRow row, params string[] NoExeFeilds) where T : BaseEntity
        {
            System.Reflection.PropertyInfo[] properties = entity.GetType().GetProperties();
            if (properties.Length > 0)
            {
                object value = null;
                foreach (System.Reflection.PropertyInfo info in properties)
                {
                    if (!EntityAttributeLib.ArrayIsExist(NoExeFeilds, info.Name))
                    {
                        if (row.Table.Columns.Contains(info.Name))
                        {
                            value = row[info.Name].ToString();
                            try
                            {
                                #region SetValue
                                ///将值做转换
                                if (info.PropertyType.Equals(typeof(string)))
                                {
                                    value = row[info.Name].ToString(); 
                                    info.SetValue(entity, value, null);
                                }
                                else if (info.PropertyType.Equals(typeof(int)))
                                {
                                    value = row[info.Name].ToString().ToInt(0);
                                    info.SetValue(entity, value, null);
                                }
                                else if (info.PropertyType.Equals(typeof(decimal)))
                                {
                                    value = row[info.Name].ToString().ToDecimal(0);
                                    info.SetValue(entity, value, null);
                                }
                                else if (info.PropertyType.Equals(typeof(DateTime)))
                                {
                                    DateTime time = new DateTime();
                                    DateTime.TryParse(row[info.Name].ToString(), out time);
                                    value = Convert.ToDateTime(time);
                                    info.SetValue(entity, value, null);
                                }
                                else if (info.PropertyType.Equals(typeof(double)))
                                {
                                    value = row[info.Name].ToString().ToFloat(0);
                                    info.SetValue(entity, value, null);
                                }
                                else if (info.PropertyType.Equals(typeof(bool)))
                                {
                                    value = row[info.Name].ToString().ToBoolean(false);
                                    info.SetValue(entity, value, null);
                                }
                                else if (info.PropertyType.Equals(typeof(Nullable<DateTime>)))
                                {
                                    if (!row[info.Name].ToString().IsNullOrWhiteSpace())
                                    {
                                        DateTime t = new DateTime();
                                        if (DateTime.TryParse(row[info.Name].ToString(), out  t))
                                        {
                                            info.SetValue(entity, t, null);
                                        }
                                    }
                                }
                                
                                #endregion
                            }
                            catch (Exception ex)
                            {
                                throw (new Exception(ex.Message));
                            }
                        }
                        else
                            throw new Exception("数据集里没有字段：" + info.Name);
                    }
                }
            }
        }
    }
}
